﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Newtonsoft.Json;
using CineProwl.Domain;

namespace CineProwl.Domain.Workers
{
    public class MovieDBService : WebRequestService, IMovieInfoService   
    {
        public Movie GetMovieInfo(int id)
        {
            string method = "Movie.getInfo";
            var result = MovieDBRequest<MovieDb.Movie[]>(method, id.ToString());
            
            if (result.Count() == 1)
            {
                return result.First().ToMovie();
            }
            else
            {
                throw new HttpUnhandledException("Get Movie Info returned " + result.Count() + " results");
            }
        }

        public List<Movie> MovieSearch(string keywords)
        {
            keywords = keywords.Replace(" ", "+");
            string method = "Movie.search";
            try
            {
                MovieDb.Movie[] movieDtos = MovieDBRequest<MovieDb.Movie[]>(method, keywords);
                List<Movie> movies = (from m in movieDtos
                                      select m.ToMovie()).ToList();
                return movies;
            }
            catch (NothingFoundMovieDBException ex)
            {
                return new List<Movie>();
            }
        }

        public Person GetPersonInfo(int id)
        {
            string method = "Person.getInfo";
            MovieDb.Person[] result = MovieDBRequest<MovieDb.Person[]>(method, id.ToString());

            if (result.Count() == 1)
            {
                return result.First().ToPerson();
            }
            else
            {
                throw new HttpUnhandledException("Get Person Info returned " + result.Count() + " results");
            }
        }

        private T MovieDBRequest<T>(string method, string parameter)
        {
            string json = "";
            string url = String.Format(Constants.URL_TEMPLATE, method, Constants.API_KEY,parameter);
            
            try 
            {
                json = this.MakeWebRequest(url);

            }
            catch (Exception ex)
            {
                throw new HttpUnhandledException("Error making request to MovieDB: " + url, ex);
            }
            if (json == "[\"Nothing found.\"]")
            {
                throw new NothingFoundMovieDBException();
            }
            try
            {
                T serializedObject = JsonConvert.DeserializeObject<T>(json);
                return serializedObject;
            }
            catch (Exception ex)
            {
                throw new JsonSerializationException("Error serializing Json response from - " + url, ex);
            }
        }
        
    }
}
